package com.reggie.serve.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.serve.common.R;
import com.reggie.serve.entity.Employee;
import com.reggie.serve.service.EmployeeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
@RequiredArgsConstructor
public class EmployeeController {
    private final EmployeeService employeeService;

    /**
     * 处理员工登录请求。
     * 通过接收来自前端的员工对象，验证员工的用户名、密码和账号状态。
     * 如果验证成功，将员工ID存储在会话中，以供后续请求使用。
     *
     * @param request  HttpServletRequest对象，用于获取会话并存储员工ID。
     * @param employee 员工对象，包含登录时提供的用户名和密码。
     * @return 如果登录成功，返回包含成功登录的员工信息的响应对象；如果登录失败，返回错误消息。
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
        if (emp == null) {
            return R.error("登录失败!");
        }
        if (!emp.getPassword().equals(password)) {
            return R.error("登录失败!");
        }
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用!");
        }
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功!");
    }

    /**
     * 该方法首先对默认密码“123456”进行MD5加密，然后为新员工对象设置加密后的密码。
     *
     * @param employee 新员工的信息对象，通过请求体传入。
     * @return 返回一个包含成功消息的响应对象。
     */
    @PostMapping("/save")
    public R<String> save(@RequestBody Employee employee) {
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);
        employeeService.save(employee);
        return R.success("新增员工成功!");
    }

    @GetMapping("/page")
    public R<Page<Employee>> page(int page, int pageSize, String name) {
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Employee::getName, name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    @PutMapping("/edit")
    public R<String> edit(@RequestBody Employee employee) {
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empId);
//        BaseContext.setCurrentId(empId);
        employeeService.updateById(employee);
        return R.success("员工信息修改成功!");
    }

    /**
     * 根据id查询员工信息
     *
     * @param id 员工ID
     * @return 如果找到员工，则返回包含员工信息的成功响应；否则，返回错误消息。
     */
    @GetMapping("query/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息!");
    }
}
